import React, { useMemo, useState } from 'react'
import { Input } from '@/components/ui/input'
import '@/app/component/form.css'
import classNames from 'classnames'
import { X } from 'lucide-react'

/** 辅助类型：根据多选状态推导值类型 */
type InputValue<T, IsNumber> = IsNumber extends true ? number | undefined : string | undefined;
interface MyInputProps<T, IsNumber extends boolean = false> {
  value?: InputValue<T, IsNumber>
  onChange?: (value: InputValue<T, IsNumber>) => void
  placeholder?: string
  disabled?: boolean
  prefix?: React.ReactNode
  suffix?: React.ReactNode
  number?: IsNumber // 绑定是否是数字输入
  max?: number
  min?: number
  precision?: number
  className?: string // 自定义类名
}

const MyInput = <T, IsNumber extends boolean = false>({
  value, 
  onChange, 
  placeholder,
  disabled, 
  suffix, 
  prefix, 
  number, 
  max, 
  min, 
  precision,
  className
}: MyInputProps<T, IsNumber>) => {
  const [isFocus, setIsFocus] = useState(false)
  // 判断是否是有效value值
  // 字符串
  const isStringValid = useMemo(() => {
    return value !== undefined && value !== ''
  }, [value])
  // 数字
  const isNumberValid = useMemo(() => {
    return value !== undefined && !isNaN(Number(value))
  }, [value])

  // 输入处理
  // 字符串
  const handleStringChange = (value: string | undefined) => {
    if (value === undefined) {
      onChange?.(undefined)
      return
    }

    if (max !== undefined && value.length > max) {
      // 截取掉最大值之后的字符串
      onChange?.(value.slice(0, max) as InputValue<T, IsNumber>)
      return
    }
    // 不处理最小值

    onChange?.(value as InputValue<T, IsNumber>)
  }

  // 数字
  const handleNumberChange = (value: string | undefined) => {
    // 处理非有效数字
    if (value === undefined || isNaN(Number(value)) || value === '') {
      onChange?.(undefined);
      return;
    }

    // // 处理最大值
    // if (max !== undefined && Number(value) > max) {
    //   onChange?.(max as InputValue<T, IsNumber>)
    //   return
    // }
    // // 处理最小值
    // if (min !== undefined && Number(value) < min) {
    //   onChange?.(min as InputValue<T, IsNumber>)
    //   return
    // }

    // 处理保留的小数位数
    if (precision !== undefined && precision >= 0) {
      // 1. 分割整数和小数部分
      const [integerPart, decimalPart] = value.split('.');
      
      // 2. 无小数部分或小数位未超精度：直接使用原字符串
      if (!decimalPart || decimalPart.length <= precision) {
        onChange?.(Number(value) as InputValue<T, IsNumber>);
        return;
      }
      
      // 3. 小数位超精度：截断后重新拼接
      const truncatedDecimal = decimalPart.slice(0, precision);
      const limitedValue = decimalPart ? `${integerPart}.${truncatedDecimal}` : integerPart;
      
      // 4. 转换为数字后传递（确保类型正确）
      onChange?.(Number(limitedValue) as InputValue<T, IsNumber>);
      return;
    }

    onChange?.(Number(value) as InputValue<T, IsNumber>)
  }

  return (
    <div className={classNames('input-layout', {
      'input-layout--focus': isFocus,
      'input-layout--disabled': disabled,
      'input-layout--placeholder': number ? !isNumberValid : !isStringValid
    }, className)}>
      {prefix}
      {/* 主要文本内容 */}
      <Input min={min} max={max} type={number ? 'number' : 'text'} className='input-text' placeholder={placeholder} value={value} onChange={(e) => number ? handleNumberChange(e.target.value) : handleStringChange(e.target.value)} onFocus={() => setIsFocus(true)} onBlur={() => setIsFocus(false)} />
      {/* 字符串最大值指示器 */}
      {!number && max !== undefined && <div className='input-text-max'>{typeof value === 'string' ? value.length : 0} / {max}</div>}
      {/* 状态指示器 */}
      <div className='input-indicator'>
        <div className='input-indicator-container'>
          <X className={classNames('input-indicator-close transition-all duration-100', {
            'hidden': number ? !isNumberValid : !isStringValid || disabled
          })}
            onClick={(e) => {
              e?.stopPropagation();
              number ? handleNumberChange('') : handleStringChange('');
            }}
          />
        </div>
      </div>
      {/* 后缀 */}
      {suffix}
    </div>
  )
}

export default MyInput